<template>
	<div class="pages">
		<div class="container">
			<!-- 任务查看 -->
			<div v-if="(route.query.type as string).substr(0, 4) == '1001'" class="task-info">
				<!-- 任务名称 -->
				<div class="text">
					<p class="title">任务名称：</p>
					<p class="content" v-text="state.taskInfo.taskName || state.taskInfo.reportTitle || ''"></p>
				</div>
				<!-- 指令编码 -->
				<div class="text">
					<p class="title">指令编码：</p>
					<p class="content" v-text="state.taskInfo.taskId || '暂无编码'"></p>
				</div>
				<!-- 指令类型 -->
				<div class="text">
					<p class="title">指令类型：</p>
					<p class="content" v-text="dictFormat(state.taskInfo.taskType)"></p>
				</div>
				<!-- 发起单位 -->
				<div class="text">
					<p class="title">发起单位：</p>
					<p class="content" v-text="state.taskInfo.createOrgName"></p>
				</div>
				<!-- 发起人 -->
				<div class="text">
					<p class="title">发起人：</p>
					<p class="content" v-text="state.taskInfo.createUserName"></p>
				</div>
				<!-- 办理期限 -->
				<div class="text">
					<p class="title">办理期限：</p>
					<p class="content" v-text="dateFormat(new Date(state.taskInfo.endHandleTime), 'yyyy-MM-dd hh:mm:ss')"></p>
				</div>
				<!-- 审批流程 -->
				<div class="text">
					<p class="title">审批流程：</p>
					<p @click.stop="toPage(paths.process, state.taskInfo.taskId)" class="content font-color-blue">点击查看</p>
				</div>
				<!-- 任务附件 -->
				<div class="text">
					<p class="title">任务附件：</p>
					<p @click="downloadAttachment(state.taskInfo.attachUrl)" class="content font-color-blue">点击下载</p>
				</div>
				<!-- 指令描述 -->
				<div class="text">
					<p class="title">指令描述：</p>
					<p class="content des-style">
						<span class="des" ref="des" v-text="state.taskInfo.taskDescription"></span>
						<span v-if="toggleIsShow(state.taskInfo.taskDescription)" @click="desToggle"
							class="show-more font-color-blue">{{ state.toggle ? '收起' : '展开' }} ></span>
					</p>
				</div>
			</div>
			<!-- 上报查看 -->
			<div v-else-if="(route.query.type as string).substr(0, 4) == '1008'" class="task-info">
				<div class="text">
					<p class="title">上报名称：</p>
					<p class="content" v-text="state.taskInfo.reportTitle"></p>
				</div>
				<div class="text">
					<p class="title">上报类型：</p>
					<p class="content" v-text="dictFormat(state.taskInfo.reportType)"></p>
				</div>
				<div class="text">
					<p class="title">发起人：</p>
					<p class="content" v-text="state.taskInfo.createUserName"></p>
				</div>
				<div class="text">
					<p class="title">接收部门：</p>
					<p class="content" v-text="state.taskInfo.receiveDeptName"></p>
				</div>
				<div class="text">
					<p class="title">接收人：</p>
					<p class="content" v-text="state.taskInfo.receiveUserName"></p>
				</div>
				<div class="text">
					<p class="title">审批流程：</p>
					<p @click.stop="toPage(paths.process, state.taskInfo.id)" class="content font-color-blue">点击查看</p>
				</div>
				<div class="text">
					<p class="title">上报附件：</p>
					<p @click="downloadAttachment(state.taskInfo.attachUrl)" class="content font-color-blue">点击下载</p>
				</div>
				<div class="text">
					<p class="title">上报描述：</p>
					<p class="content des-style">
						<span class="des" ref="des" v-text="state.taskInfo.reportContent"></span>
						<span v-if="toggleIsShow(state.taskInfo.reportConten)" @click="desToggle"
							class="show-more font-color-blue">{{ state.toggle ? '收起' : '展开' }} ></span>
					</p>
				</div>
			</div>
			<!-- <div class="task-update">
				<van-action-sheet v-model:show="state.taskUpdate.show" title="任务-修改">
					<div class="form">
						<van-form @submit="ontaskUpdateSubmit">
							<van-cell-group inset>
								<van-field v-model="state.taskUpdate.form.taskName" name="taskName" label="任务名称" placeholder="请输入任务名称"
									:rules="[{ required: true, message: '请输入任务名称' }]" />
							</van-cell-group>
							<div style="margin: 16px;">
								<van-button round block type="primary" native-type="submit">
									修改
								</van-button>
							</div>
						</van-form>
					</div>
				</van-action-sheet>
			</div> -->
			<!-- 发送平台 star -->
			<div v-if="state.taskInfo.taskStatus == 1" class="taskbar">
				<div class="title">
					<div class="line"></div>
					<div class="text" v-text="lists.title"></div>
				</div>
				<div @click="toPage(paths.platfromsend, route.query.taskId)" class="badge" v-text="lists.badge"></div>
			</div>
			<div v-if="state.taskInfo.taskStatus == 1" class="lists-module-tips">
				<div class="lists">
					<van-pull-refresh class="pull-refresh" v-model="lists.refresh.loading" @refresh="onRefresh">
						<van-list v-model:loading="lists.more.loading" :finished="lists.more.finished" finished-text="没有更多了"
							@load="onLoad">
							<div class="item" @click="detail(item)" v-for="(item, idx) in lists.lists" :key="idx">
								<div class="info">
									<div class="circle"></div>
									<div class="text">
										<div class="content" v-text="item.targetOrgName"></div>
										<div class="label text-overflow">
											<span class="company" v-text="'接收人：' + item.recipientName"></span>
										</div>
									</div>
								</div>
								<van-divider />
							</div>
						</van-list>
					</van-pull-refresh>
				</div>
			</div>
			<van-popup v-if="state.taskInfo.taskStatus == 1" v-model:show="lists.detail.show" position="bottom"
				close-on-popstate :style="{ height: '30%' }">
				<div class="popup-container">
					<div class="tools">
						<div class="cancel" @click="lists.detail.show = false">取消</div>
						<div class="del">删除信息</div>
					</div>
					<van-divider class="line" />
					<div class="content">
						<div class="text">
							<div class="title" v-text="'平台名称：'"></div>
							<div class="value" v-text="lists.detail.info.targetOrgName"></div>
						</div>
						<div class="text">
							<div class="title" v-text="'属地单位：'"></div>
							<div class="value" v-text="lists.detail.info.company"></div>
						</div>
						<div class="text">
							<div class="title" v-text="'接收人：'"></div>
							<div class="value" v-text="lists.detail.info.recipientName"></div>
						</div>
						<div class="text">
							<div class="title" v-text="'联系方式：'"></div>
							<div class="value" v-text="lists.detail.info.recipientUserPhone"></div>
						</div>
					</div>
				</div>
			</van-popup>
			<!-- 发送平台 end -->
			<!-- 反馈办理 star -->
			<div v-if="state.taskInfo.taskStatus != 1" class="taskbar">
				<div class="title">
					<div class="line"></div>
					<div class="text" v-text="form.title"></div>
				</div>
				<div v-if="form.badge" class="badge" v-text="form.badge"></div>
			</div>
			<div v-if="state.taskInfo.taskStatus != 1" class="submit">
				<van-form ref="formDom">
					<van-steps direction="vertical" :active="0" active-color="#4674C9">
						<van-step>
							<template v-slot:active-icon>
								<div class="circle active"></div>
							</template>
							<template v-slot:inactive-icon>
								<div class="circle"></div>
							</template>
							<template v-slot:default>
								<div class="label">
									<span class="text">反馈内容</span>
								</div>
								<van-field
									v-model="form.submit.feedbackContent"
									rows="2"
									autosize
									type="textarea"
									maxlength="500"
									show-word-limit
									name="feedbackContent"
									placeholder="请输入反馈内容"
									:rules="[{ required: false, message: '请输入反馈内容' }]" />
							</template>
						</van-step>
						<van-step>
							<template v-slot:active-icon>
								<div class="circle active"></div>
							</template>
							<template v-slot:inactive-icon>
								<div class="circle"></div>
							</template>
							<template v-slot:default>
								<div class="label">
									<span class="text">反馈附件</span>
								</div>
								<van-field name="feedbackFileId">
									<template #input>
										<van-uploader multiple :max-count="2" :before-read="beforeRead" :after-read="afterRead"
											v-model="form.submit.feedbackFileId" />
									</template>
								</van-field>
							</template>
						</van-step>
						<van-step>
							<template v-slot:active-icon>
								<div class="circle active"></div>
							</template>
							<template v-slot:inactive-icon>
								<div class="circle"></div>
							</template>
							<template v-slot:default>
								<div class="label">
									<span class="require">*</span>
									<span class="text">审批人</span>
								</div>
								<van-field name="approval" :rules="[{ required: true, message: '请选择审批人' }]"
									v-model="form.user.active.text" is-link readonly placeholder="请选择审批人"
									@click="form.user.show = true" />
								<van-popup v-model:show="form.user.show" position="bottom">
									<van-picker :loading="form.user.loading" :columns="form.user.columns" @cancel="form.user.show = false"
										@confirm="onConfirm" />
								</van-popup>
							</template>
						</van-step>
					</van-steps>
				</van-form>
			</div>
			<!-- 反馈办理 end -->
		</div>
		<div v-if="state.taskInfo.taskStatus == 1" class="menu">
			<div class="btn blue btn-w-3" @click="state.taskUpdate.show = true">修改</div>
			<div class="btn blue btn-w-3" @click="toPage(paths.send, route.query.taskId)">发送</div>
			<div class="btn red btn-w-3" @click="toPage(paths.sendback, route.query.taskId)">退回</div>
		</div>
		<div v-else-if="state.taskInfo.taskStatus != 1" class="menu">
			<div class="btn blue btn-w-2" @click="m_approval">办理发送</div>
			<div class="btn blue btn-w-2" @click="m_forwardTask">转发办理</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { dictinfo, taskInfo, platformReportInfo, taskUpdate, tasktargetinfo, taskInfoTime, getTaskApproval, approval, forwardTask, reportInfoTime, downloadFile } from '@/api/todo'
import { Page } from '@/api/types/public'
import { deepClone, dateFormat } from '@/utils/utils'
import { uploadFile } from '@/api/file';
import Toast from 'vant/lib/toast'
import { downloadAttachment } from '@/utils/file'

const route = useRoute();
const router = useRouter();

const state = reactive({
	taskInfo: {} as any,
	toggle: false,
	taskUpdate: {
		show: false,
		form: {
			taskName: ''
		} as any
	},
	dict: {
		taskType: [] as any,
		reportType: [] as any
	}
})

const lists = reactive({
	refresh: {
		loading: false
	},
	more: {
		loading: false,
		finished: false
	},
	pages: {
		page: 1,
		size: 10
	} as Page,
	title: '发送平台',
	badge: 1127,
	lists: [] as any,
	detail: {
		show: false,
		info: {} as any
	}
})

const form = reactive({
	title: '反馈办理',
	badge: 0,
	user: {
		active: {
			text: '',
			value: ''
		},
		show: false,
		loading: true,
		columns: [] as any
	},
	active: 0,
	lists: [] as any,
	submit: {
		feedbackContent: '',
		feedbackFileId: [],
		approver: ''
	} as any
})

const des = ref();
// 描述展开收起
const desToggle = () => {
	state.toggle = !state.toggle;
	if (state.toggle) {
		des.value.style['-webkit-line-clamp'] = 'inherit';
		des.value.style['overflow'] = 'visible';
	} else {
		des.value.style['-webkit-line-clamp'] = '2';
		des.value.style['overflow'] = 'hidden';
	}
}

// 下拉刷新回调
const onRefresh = () => {
	// 清空列表数据
	lists.more.finished = false
	lists.pages.page = 1
	// 重新加载数据
	// 将 loading 设置为 true，表示处于加载状态
	lists.more.loading = true
	onLoad();
}

// 加载更多回调
const onLoad = async () => {
	const params = {
		taskId: route.query.taskId as string,
		page: lists.pages.page,
		size: lists.pages.size,
	}
	try {
		const res = await tasktargetinfo(params)

		let temp = res.data.records
		lists.badge = res.data.total
		if (lists.refresh.loading) {
			lists.lists = [];
			lists.refresh.loading = false;
		}
		lists.lists.push(...temp);
		lists.more.loading = false;

		lists.pages.page++

		if (!temp.length) {
			lists.more.finished = true;
		} else {
			lists.more.finished = false;
		}
	} catch (error: any) {
		lists.refresh.loading = false;
		lists.more.loading = false;
		lists.more.finished = true;
	}
}

// 发送平台详情
const detail = (info: any) => {
	lists.detail.info = info;
	lists.detail.show = true;
}

const paths = reactive({
	send: '/todo/taskapprovalsend',
	sendback: '/todo/taskapprovalsendback',
	process: '/todo/taskapprovalprocess',
	platfromsend: '/todo/taskplatfromsend'
})

const toPage = (path: any, id: any = {}) => {
	router.push({
		path, query: {
			id: id,
			type: (<string>route.query.type).substr(0, 4)
		}
	})
}

const toggleIsShow = (str: any) => {
	return typeof str == 'string' && str.length > 30
}


const onConfirm = (item: any) => {
	form.user.active.text = item.text;
	form.user.active.value = item.value;
	form.submit.approver = item.value;
	form.user.show = false;
}

const initProcess = async (taskId: string) => {
	const res = (<string>route.query.type).substr(0, 4) == '1001' ? await taskInfoTime({ taskId: taskId }) : await reportInfoTime({ id: taskId })
	const data = res.data
	form.lists = data
	// 判断流程到第几步
	const index = form.lists.findIndex((item: any) => {
		if (item) return item.approvalStatus == '0'
	})

	if (index != -1) {
		form.active = index
	} else {
		form.active = form.lists.length - 1
	}
	initTaskApproval(form.lists[form.active].customSeqId)
}

const initTaskApproval = async (seqId: string) => {
	const res = await getTaskApproval({ seqId })
	const data = res.data
	const pickers = data.map((item: any) => {
		item.text = item.appUserName
		item.value = item.appUserId
		return item
	})
	form.user.columns = [...pickers]
	form.user.loading = false
}

const formDom = ref()
const m_approval = () => {
	formDom.value.validate().then(async () => {
		const submit = formDom.value.getValues()
		if (submit.approval) {
			let params = {
				approvalUserId: form.user.active.value,
				taskId: route.query.taskId as string,
				isApproval: true
			}
			const res = await approval(params)
			res.code == 0 && res.data == true &&
				Toast({
					message: '发送成功',
					position: 'bottom',
					onClose: () => {
						router.back()
					}
				});
			res.code == 500 &&
				Toast({
					message: res.msg,
					position: 'bottom'
				});
		} else {
			Toast({
				message: '请选择审批人',
				position: 'bottom'
			});
		}
	}).catch((error: any) => {
		console.log('formError', error)
	})
}

const m_forwardTask = () => {
	formDom.value.validate().then(async () => {
		const submit = formDom.value.getValues()
		if (submit.approval) {
			let params = {
				taskTargetId: route.query.taskId as string,
				forwardTaskUserId: form.user.active.value,
			}
			const res = await forwardTask(params)
			res.code == 0 && res.data == true &&
				Toast({
					message: '发送成功',
					position: 'bottom',
					onClose: () => {
						router.back()
					}
				});
			res.code == 500 &&
				Toast({
					message: res.msg,
					position: 'bottom'
				});
		} else {
			Toast({
				message: '请选择审批人',
				position: 'bottom'
			});
		}
	}).catch((error: any) => {
		console.log('formError', error)
	})
}

const ontaskUpdateSubmit = async () => {
	const res = await taskUpdate(state.taskUpdate.form)
	console.log('form', state.taskUpdate.form, res);
}

// const onSubmit = () => {
// 	console.log('form', form.submit);
// }

const initData = async (params: any) => {
	const type = params.type.substr(0, 4)
	let res
	switch (type) {
		case '1001':
			res = await taskInfo(params.id)
			break
		case '1008':
			res = await platformReportInfo(params.id)
			break
		default:
			res = await taskInfo(params.id)
			break
	}
	const data = res.data
	state.taskInfo = deepClone(data)
	state.taskUpdate.form = deepClone(data)
}

//字典查询
const initDict = async (dictCode: string, field: { value: string, text: string }, callback: Function) => {
	const res = await dictinfo(dictCode)

	const children = res.data.map((item: any) => {
		item[field.value || 'value'] = item.dictCode
		item[field.text || 'text'] = item.dictName
		return item
	})

	callback(children)
}

// 字典回显
const dictFormat = (code: any) => {
	const item = state.dict[(route.query.type as string).substr(0, 4) == '1001' ? 'taskType' : 'reportType']?.find((item: any) => {
		return code === item.value
	}) as any
	return item ? item.text : code
}

// 上传前置
const beforeRead = (file: any): any => {
	return true
}

// 上传后
const afterRead = (file: any): any => {
	console.log('after', file)
	uploadFile(file, (data) => {
		console.log('data', data)
	}).then((res) => {
		console.log('res', res)
	})
}

onMounted(() => {
	initData(route.query)
	const format = { value: 'value', text: 'text' }
	initDict('1001', format, (children: Array<any>) => {
		state.dict.taskType = children
	})
	initDict('1008', format, (children: Array<any>) => {
		state.dict.reportType = children
	})
	initProcess(route.query.id as string)
})
</script>
<style lang="scss" scoped>
.pages {
	height: 100%;
	display: flex;
	flex-direction: column;

	.container {
		flex: 1;
		height: 0;
		box-sizing: border-box;
		padding: 12px;
		display: flex;
		flex-direction: column;

		.task-info {
			background: #ffffff;
			border-radius: 5px;
			box-shadow: 0.5px 0.87px 4.5px 1px rgba(0, 0, 0, 0.05);
			box-sizing: border-box;
			padding: 16px 12px;

			.text {
				margin-bottom: 12px;
				display: flex;
				align-items: center;

				.title {
					white-space: nowrap;
					font-size: 14px;
					font-weight: bold;
					color: #181818;
					text-align: justify;
					text-align-last: justify;
					width: 22%;
				}

				.content {
					flex: 1;
					font-size: 14px;
					font-weight: bold;
					text-align: left;
					color: #646464;
					position: relative;

					.show-more {
						font-size: 12px;
						position: absolute;
						right: 0;
						bottom: 0;
					}
				}

				.des-style {
					padding-right: 40px;
				}

				.des {
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					overflow: hidden;
				}

				.font-color-blue {
					color: $primary-color
				}
			}
		}

		//任务待办
		.taskbar {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.title {
				display: flex;
				align-items: center;
				margin: 16px 0;

				.line {
					width: 4px;
					height: 16px;
					margin-right: 8px;
					background-color: $primary-color;
				}

				.text {
					font-weight: 700;
					text-align: left;
					color: #181818;
					line-height: 12px;
				}
			}

			.badge {
				width: 29px;
				height: 16px;
				border-radius: 8.5px;
				background-color: $primary-color;
				text-align: center;
				line-height: 16px;
				font-size: 10px;
				font-weight: bold;
				color: #fff;
			}
		}

		// 列表模板-提示
		.lists-module-tips {
			background: #ffffff;
			border-radius: 5px;
			box-shadow: 0.5px 0.87px 4.5px 1px rgba(0, 0, 0, 0.05);
			box-sizing: border-box;
			flex: 1;
			height: 0;
			overflow-y: scroll;

			.lists {
				padding-top: 16px;

				.item {
					display: flex;
					flex-direction: column;
					padding: 0 12px 0 12px;

					.info {
						display: flex;
						flex-direction: row;

						.circle {
							width: 4px;
							height: 4px;
							background-color: $primary-color;
							border-radius: 50%;
							margin-top: 6px;
							margin-right: 8px;
						}

						.text {
							flex: 1;

							.content {
								font-size: 14px;
								font-weight: bold;
								text-align: left;
								color: #181818;
								line-height: 16px;
								margin-bottom: 8px;
							}

							.label {
								font-size: 10px;
								font-weight: bold;
								text-align: left;
								color: #646464;
								line-height: 16px;
								white-space: nowrap;

								.company {
									margin-right: 4px;
								}

								.date {
									margin-left: 4px;
								}
							}
						}
					}
				}
			}
		}

		.submit {
			background: #ffffff;
			border-radius: 5px;
			box-shadow: 0.5px 0.87px 4.5px 1px rgba(0, 0, 0, 0.05);
			box-sizing: border-box;
			padding: 16px 12px;
			flex: 1;
			height: 0;
			overflow-y: scroll;

			&:deep(.van-hairline) {
				&:after {
					content: none;
				}
			}

			&:deep(.van-cell) {
				background-color: #FFFFFF;
				border: 0.5px solid #F7F7F7;
				border-radius: 5px;
				padding: 4px 8px;
				font-size: 10px;

				&:after {
					content: none;
				}
			}

			.label {
				margin-bottom: 8px;

				.require {
					color: #DA0000;
				}

				.text {
					font-size: 14px;
					font-weight: bold;
					color: #181818;
				}
			}

			.circle {
				width: 5px;
				height: 5px;
				border-radius: 50%;
				background-color: #ffffff;
				border: 3px solid #ECECEC;
			}

			.active {
				border-color: $primary-color !important;
			}
		}
	}

	.popup-container {
		.tools {
			display: flex;
			align-items: center;
			justify-content: space-between;
			box-sizing: border-box;
			padding: 9px 12px;

			.cancel {
				font-size: 14px;
				font-weight: bold;
				color: #646464;
			}

			.del {
				font-size: 14px;
				font-weight: bold;
				color: #ef0d0d;
			}
		}

		.line {
			margin-top: 0;
		}

		.content {
			box-sizing: border-box;
			padding: 16px 24px;

			.text {
				display: flex;
				align-items: center;
				margin-bottom: 16px;

				&:last-child {
					margin-bottom: 0;
				}

				.title {
					font-size: 14px;
					font-weight: bold;
					color: #181818;
				}

				.value {
					font-size: 14px;
					font-weight: bold;
					color: #646464;
				}
			}
		}
	}

	.menu {
		display: flex;
		align-items: center;
		justify-content: space-evenly;
		box-sizing: border-box;
		padding: 10px 0;
		background: #ffffff;
		box-shadow: 0px -1px 2.5px 1px rgba(0, 0, 0, 0.03), -0.5px 0px 0px 0.5px #ebebeb inset;

		.btn {
			box-sizing: border-box;
			padding: 8px 0;
			border-radius: 5px;
			font-size: 14px;
			font-weight: bold;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.btn-w-3 {
			width: 30%;
		}

		.btn-w-2 {
			width: 45%;
		}

		.blue {
			color: $primary-color;
			background-color: #F1F4FF;
		}

		.red {
			color: #EF0D0D;
			background-color: #FFF1F2;
		}
	}
}
</style>